package com.atguigu.guli.gateway.filters;

import com.atguigu.guli.service.base.JwtHelper;
import com.atguigu.guli.service.result.ResultCodeEnum;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.swing.*;
import java.nio.charset.StandardCharsets;

@Component
public class GateFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求路径是否满足鉴权的格式  反射路径带有auth都是需要鉴权
        String path = request.getURI().getPath(); // 获取端口号中间地址就是controller层的隐射地址
        AntPathMatcher matcher = new AntPathMatcher();
        boolean b = matcher.match("/**/auth/**", path);  //验证是否符合需要鉴权,满足地址中有auth就要鉴权
        if(b){
            //获取请求中的token
            String token = request.getHeaders().getFirst("token");
            boolean checkToken = JwtHelper.checkToken(token);
            if (!checkToken){
                //如果不通过,说明没有登录,响应前端一个json,于R对象一直
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("code", ResultCodeEnum.LOGIN_ACL.getCode());
                jsonObject.addProperty("message", ResultCodeEnum.LOGIN_ACL.getMessage());
                jsonObject.addProperty("success", ResultCodeEnum.LOGIN_ACL.getSuccess());
                // 响应字符串
                String json = jsonObject.toString();
                DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));

                //添加头,指定响应题内容
                response.getHeaders().setContentType(MediaType.valueOf("application/json;charset=UTF-8"));
                System.out.println("呜呜呜呜呜呜呜");
                return response.writeWith(Mono.just(dataBuffer));
            }
        }
        //不去要鉴权是,直接放行
        return chain.filter(exchange);
    }
}
